using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Text;


namespace PHSRAG.Insight21.FormsManagement.Serialization
{
	/// <summary>
	/// QuestionnaireSerializer - a utility class that serializes Questionnaires
	/// </summary>
	public class QuestionnaireSerializer
	{
		/// <summary>
		/// Serializes the object passed in as a parameter
		/// </summary>
		/// <param name="serializableObject">Object to be serialized</param>
		/// <returns>XML string</returns>
		public static string Serialize(object serializableObject)
		{
			string sXML = string.Empty;

			StringWriterWithEncoding encodedWriter = new StringWriterWithEncoding(Encoding.UTF8);
			try
			{
				XmlSerializerNamespaces xmlSerializerNS = new XmlSerializerNamespaces(); 
				xmlSerializerNS.Add("", ""); 
				XmlSerializer serializer = new XmlSerializer(serializableObject.GetType());
				

				serializer.Serialize( new XmlTextWriter(encodedWriter), serializableObject, xmlSerializerNS);
				sXML = encodedWriter.ToString();
			}
			catch (Exception ex)
			{
				Utility.ExceptionReport.WriteToEventLog ("Failed to serialize Questionnaire", ex, true, Utility.ExceptionReport.ReportType.Error);
				throw(ex);
			}
			finally
			{
				encodedWriter.Close();
				
			}

			return sXML;
		}

		

		/// <summary>
		/// String Writer class with overridden Encoding method.
		/// 
		/// This class is created to support the conversion of Application xml to pdf which requires that the encoding used is UTF-8 and not UTF-16
		/// </summary>
		public class StringWriterWithEncoding : StringWriter
		{
			Encoding encoding;

			public StringWriterWithEncoding (Encoding encoding)
			{
				this.encoding = encoding;
			}

			public override Encoding Encoding
			{
				get { return encoding; }
			}
		}
	}
}
